/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\classificationManage\classificationComponents\EditClassification.tsx
 * @Description  : 修改分类模态框
 */

import {
  checkClassificationNameExist,
  checkClosedLoopExist,
  getClassificationInfo,
  getFatherClassificationList,
  saveClassificationInfo,
} from '@/services/classification';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { message, Modal } from 'antd';
import React, { useRef, useState } from 'react';

type LayoutType = Parameters<typeof ProForm>[0]['layout'];

/**
 * 修改分类模态框，将父级传来的数据结构，并实现修改分类功能
 * @param props
 * @returns
 */
const EditClassification = (props: {
  isModalVisible?: any;
  isShowModal?: any;
  actionRef?: any;
  aid?: any;
}) => {
  const { isModalVisible } = props;
  const { isShowModal } = props;
  const { actionRef } = props;
  const { aid } = props;
  const [formLayoutType] = useState<LayoutType>('horizontal');
  const [flagName, setFlagName] = useState<boolean>(true);
  const [flagId, setFlagId] = useState<boolean>(true);
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };

  /**
   * 获取要修改的分类信息
   * @returns
   */
  const getClassificationDate = async () => {
    const param = {
      aid: aid,
    };
    const response = await getClassificationInfo(param);
    return response;
  };

  /**
   * 修改分类
   */
  const formRef = useRef<
    ProFormInstance<{
      aid: number;
      name: string;
      fatherAid?: number;
    }>
  >();
  const handleOk = async () => {
    if (flagId === undefined) {
      setFlagId(true);
    }
    if (flagName && flagId) {
      const data = await formRef.current?.validateFields();
      const param = {
        aid: aid,
        name: data?.name || '',
        fatherAid: data?.fatherAid || -1,
      };
      const response = await saveClassificationInfo(param);
      if (response) {
        message.success('修改成功！');
        isShowModal(false);
        actionRef.current.reload();
      } else {
        message.error('修改失败！');
      }
    } else {
      message.error('你有校验没通过，请检查！！');
    }
  };

  return (
    <Modal
      destroyOnClose
      title="修改"
      width="649px"
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={() => {
        isShowModal();
        setFlagId(true);
        setFlagName(true);
      }}
    >
      <ProForm
        //渲染要修改的分类信息
        request={() => getClassificationDate()}
        formRef={formRef}
        submitter={{
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        {...layout}
        layout={formLayoutType}
        params={{}}
      >
        <ProFormText
          name="name"
          label="名称"
          placeholder="请输入"
          validateStatus={flagName ? 'success' : 'error'}
          fieldProps={{
            //分类名称的唯一性校验
            onBlur: async (event) => {
              const params = {
                aid: aid,
                name: event.target.value,
              };
              if (params.name) {
                const response = await checkClassificationNameExist(params);
                if (response.isExist) {
                  message.error('该分类名称已经存在！！');
                  setFlagName(false);
                } else {
                  setFlagName(true);
                }
              }
            },
          }}
          rules={[{ required: true }]}
        />
        <ProFormSelect
          name="fatherAid"
          label="父级类型"
          placeholder="请输入"
          validateStatus={flagId ? 'success' : 'error'}
          fieldProps={{
            //分类名称的闭环校验
            onSelect: async (value) => {
              const params = {
                aid,
                fatherAid: value,
              };
              const response = await checkClosedLoopExist(params);
              if (response.isExist) {
                message.error('该分类名称产生闭环！！');
                setFlagId(false);
              } else {
                setFlagId(true);
              }
            },
          }}
          request={async () => {
            const data = await getFatherClassificationList();
            return data.map((item: { name: any; aid: any }) => {
              return {
                label: item.name,
                value: item.aid,
              };
            });
          }}
        />
      </ProForm>
    </Modal>
  );
};

export default EditClassification;
